export async function* countingSort(array, compare, swap, set) {
    const n = array.length;
    if (n <= 1) {
        yield { type: 'complete' };
        return;
    }

    // Find the maximum value in the array
    let max = array[0];
    for (let i = 1; i < n; i++) {
        if (array[i] > max) max = array[i];
    }

    // Initialize count array
    const count = new Array(max + 1).fill(0);
    
    // Store count of each element
    for (let i = 0; i < n; i++) {
        count[array[i]]++;
        yield { type: 'compare', indices: [i] };
    }

    // Build the output array
    let outputIndex = 0;
    for (let i = 0; i <= max; i++) {
        while (count[i] > 0) {
            array[outputIndex] = i;
            yield { type: 'set', index: outputIndex, value: i };
            count[i]--;
            outputIndex++;
        }
    }

    yield { type: 'complete' };
}